import { defineStore } from 'pinia'

// Chrome窗口数据接口
export interface ChromeWindow {
  id: number
  number: number
  title: string
}

// 屏幕信息接口
export interface ScreenInfo {
  id: number
  index: number
  width: number
  height: number
  isPrimary: boolean
  workArea: {
    x: number
    y: number
    width: number
    height: number
  }
}

// 同步状态接口
export interface SyncState {
  isSyncing: boolean
  mainWindowId: number | null
  syncedWindowIds: number[]
  syncOptions: {
    mouse: boolean
    keyboard: boolean
    scroll: boolean
  }
}

// 创建全局状态管理
export const useGlobalStore = defineStore('global', {
  state: () => ({
    // Chrome窗口数据
    chromeWindows: [] as ChromeWindow[],
    selectedWindows: [] as number[],
    
    // 屏幕信息
    screens: [] as ScreenInfo[],
    primaryScreen: null as ScreenInfo | null,
    
    // 同步状态
    syncState: {
      isSyncing: false,
      mainWindowId: null,
      syncedWindowIds: [],
      syncOptions: {
        mouse: true,
        keyboard: true,
        scroll: true
      }
    } as SyncState,
    
    // 应用设置
    settings: {
      chromePath: '',
      defaultUserDataDir: '',
      defaultShortcutDir: '',
      defaultWidth: 1024,
      defaultHeight: 768,
      defaultSpacing: 10,
      autoStartChrome: true,
      rememberWindowPositions: true,
      checkUpdates: true,
      hotkeys: {
        importWindows: 'Ctrl+I',
        closeAllWindows: 'Ctrl+Shift+C',
        arrangeWindows: 'Ctrl+Shift+A',
        startSync: 'Ctrl+Shift+S',
        stopSync: 'Ctrl+Shift+X'
      }
    },
    
    // UI状态
    loading: false,
    currentView: 'window-manager',
    lastWindowNumber: 0
  }),
  
  getters: {
    // 获取选中的窗口对象数组
    selectedWindowsList: (state) => {
      return state.chromeWindows.filter(window => state.selectedWindows.includes(window.id))
    },
    
    // 检查是否正在同步
    isSyncing: (state) => {
      return state.syncState.isSyncing
    },
    
    // 获取主窗口信息
    mainWindow: (state) => {
      if (!state.syncState.mainWindowId) return null
      return state.chromeWindows.find(window => window.id === state.syncState.mainWindowId) || null
    },
    
    // 获取同步窗口数量
    syncedWindowCount: (state) => {
      return state.syncState.syncedWindowIds.length
    },
    
    // 生成下一个窗口编号
    nextWindowNumber: (state) => {
      return state.lastWindowNumber + 1
    }
  },
  
  actions: {
    // 更新Chrome窗口列表
    updateChromeWindows(windows: ChromeWindow[]) {
      this.chromeWindows = windows
      // 找出最大的窗口编号
      if (windows.length > 0) {
        this.lastWindowNumber = Math.max(...windows.map(w => w.number))
      }
    },
    
    // 更新选中的窗口
    updateSelectedWindows(windowIds: number[]) {
      this.selectedWindows = windowIds
    },
    
    // 切换窗口选中状态
    toggleWindowSelection(windowId: number) {
      const index = this.selectedWindows.indexOf(windowId)
      if (index > -1) {
        this.selectedWindows.splice(index, 1)
      } else {
        this.selectedWindows.push(windowId)
      }
    },
    
    // 全选/取消全选
    selectAllWindows(selectAll = true) {
      if (selectAll) {
        this.selectedWindows = this.chromeWindows.map(window => window.id)
      } else {
        this.selectedWindows = []
      }
    },
    
    // 移除窗口（当窗口关闭时）
    removeWindow(windowId: number) {
      const index = this.chromeWindows.findIndex(window => window.id === windowId)
      if (index > -1) {
        this.chromeWindows.splice(index, 1)
      }
      
      // 从选中列表中移除
      const selectedIndex = this.selectedWindows.indexOf(windowId)
      if (selectedIndex > -1) {
        this.selectedWindows.splice(selectedIndex, 1)
      }
      
      // 如果是主窗口，停止同步
      if (this.syncState.mainWindowId === windowId) {
        this.stopSync()
      }
      
      // 从同步窗口列表中移除
      const syncIndex = this.syncState.syncedWindowIds.indexOf(windowId)
      if (syncIndex > -1) {
        this.syncState.syncedWindowIds.splice(syncIndex, 1)
      }
    },
    
    // 更新屏幕信息
    updateScreens(screens: ScreenInfo[]) {
      this.screens = screens
      this.primaryScreen = screens.find(screen => screen.isPrimary) || null
    },
    
    // 开始同步
    startSync(mainWindowId: number, windowIds: number[], syncOptions?: Partial<SyncState['syncOptions']>) {
      this.syncState.isSyncing = true
      this.syncState.mainWindowId = mainWindowId
      this.syncState.syncedWindowIds = windowIds
      
      if (syncOptions) {
        this.syncState.syncOptions = { ...this.syncState.syncOptions, ...syncOptions }
      }
    },
    
    // 停止同步
    stopSync() {
      this.syncState.isSyncing = false
      this.syncState.mainWindowId = null
      this.syncState.syncedWindowIds = []
    },
    
    // 更新同步选项
    updateSyncOptions(options: Partial<SyncState['syncOptions']>) {
      this.syncState.syncOptions = { ...this.syncState.syncOptions, ...options }
    },
    
    // 更新设置
    updateSettings(newSettings: Partial<typeof this.settings>) {
      this.settings = { ...this.settings, ...newSettings }
    },
    
    // 设置加载状态
    setLoading(isLoading: boolean) {
      this.loading = isLoading
    },
    
    // 更新当前视图
    setCurrentView(viewName: string) {
      this.currentView = viewName
    },
    
    // 重置状态
    resetState() {
      this.chromeWindows = []
      this.selectedWindows = []
      this.stopSync()
      this.loading = false
    }
  }
})